const AppConfig = {
	homeIndex: 'homeIndex'
}

/**
 * 自动计算项目根路径
 * @returns {string} 基础路径
 */
function getBasePath() {
	const pathSegments = window.location.pathname.split('/');
	// 根据项目实际目录层级调整slice参数
	return pathSegments.slice(0, -3).join('/') || '/';
}

getRootPath = () => getBasePath() + '/';

/**
 * 页面跳转相关
 */
navigateTo = (url) => {
	if (url) {
		window.location.href = getRootPath() + url
	}
}

openNewPage = (url) => {
	if (url) {
		parent.window.open(url, "_blank");
	}
}

replacePage = (url) => {
	window.location.replace(url)
}

getValueByParam = (name) => {
	return new URLSearchParams(window.location.search).get(name);
}

setHomeIndex = i => {
	window.sessionStorage.setItem(AppConfig.homeIndex, i);
}

getHomeIndex = () => {
	return window.sessionStorage.getItem(AppConfig.homeIndex);
}

toObjectStr = (e) => {
	return JSON.stringify(e).replace(/"/g, '&quot;');
}

toObject = (e) => {
	return JSON.parse(e);
}

ArrayEmpty = (arr) => {
	if (Array.isArray(arr)) {
		if (arr.length > 0) {
			return false
		} else {
			return true
		}
	}
	return true
}

// 辅助函数：防止XSS攻击
escapeHtml = (str) => {
	return str.replace(/&/g, "&amp;")
		.replace(/</g, "&lt;")
		.replace(/>/g, "&gt;");
}

// const escapeHtml = (str) => {
// 	const div = document.createElement('div');
// 	div.textContent = str;
// 	return div.innerHTML;
// };

isEmpty = (param) => {
	if (null == param || "null" == param || param.length == 0 || 'undefined' == param) {
		return true;
	}
	return false;
}

isValidPhoneNumber = (phoneNumber) => {
	const regExp = /^1[0-9]{10}$/; // 以1开头，后面跟10位数字
	return regExp.test(phoneNumber);
}

/**
 * 将手机号码中间四位替换为星号(*)
 */
maskPhoneNumber = (phoneNumber) => {
	return phoneNumber.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
}

onCallphone = (phone) => {
	event.stopImmediatePropagation(); //阻止事件分发
	if (!isEmpty(phone)) {
		window.location.href = `tel:${phone}`;
	}
}

goBack = () => setTimeout(() => {
	window.history.go(-1);
}, 500)

setPageTitle = (text) => {
	document.title = text
}

setStorageValue = (key, value) => {
	window.localStorage.setItem(key, value)
}

getStorageValue = (key) => {
	return window.localStorage.getItem(key)
}

storageClear = () => {
	window.localStorage.clear();
	window.location.reload();
}

/**
 *  防抖函数
 *  @param fn：需要防抖的函数（也就是被频繁触发的函数）
 *  @param delay：毫秒数（设定的时间间隔）
 */
debounce = (fn, delay) => {
	let timeout = null;
	return function(...arguments) {
		let context = this;
		let args = arguments;
		if (timeout) clearTimeout(timeout);
		let callNow = !timeout;
		timeout = setTimeout(() => {
			timeout = null;
		}, delay);
		if (callNow) {
			fn.apply(context, args)
		} else {
			showToast('别点太快啦！')
		};
	};
}

/**
 *  节流函数
 *  @param fn：需要节流的函数（被连续触发的函数）
 *  @param delay：毫秒数（设定的时间）
 */
throttle = (fn, delay = 500) => {
	let lastTime = 0;
	return function(...args) {
		const now = Date.now();
		if (now - lastTime >= delay) {
			fn.apply(this, args);
			lastTime = now;
		}
	}
}
